import tkinter as tk
from tkinter import ttk
from logic.button_handlers import *
from logic.history_window import show_history
from logic.keybindings import setup_keybindings

# -----------------------------
# 主题色定义
# -----------------------------
ICE_BLUE   = "#A6E3E9"
SNOW_WHITE = "#E8F9FD"
DARK_BLUE  = "#1B6B93"

# -----------------------------
# 窗口初始化
# -----------------------------
root = tk.Tk()
root.title("⑨章计算器")
root.geometry("400x600")
root.minsize(500, 800)
root.resizable(True, True)
root.iconbitmap("logo.ico")
root.configure(bg=SNOW_WHITE)

# -----------------------------
# 状态容器
# -----------------------------
expression_state = {'expression': "", 'just_evaluated': False}
result_state     = {'result': ""}

expression_var = tk.StringVar()
result_var     = tk.StringVar()

# -----------------------------
# ttk 样式
# -----------------------------
style = ttk.Style()
style.theme_use("default")
style.configure("Calc.TButton",
    font=("微软雅黑", 16),
    background=ICE_BLUE,
    foreground=DARK_BLUE,
    borderwidth=0,
    padding=5
)
style.map("Calc.TButton",
    background=[("active", SNOW_WHITE)],
    foreground=[("active", DARK_BLUE)]
)

# -----------------------------
# 显示更新与外部调用
# -----------------------------
def update_display():
    # expression 用 ** 存储，但 UI 显示为 ^
    expression_var.set(expression_state['expression'].replace('**', '^'))
    result_var.set(result_state['result'])

def set_expression(expr_str):
    # 来自“历史记录”时调用
    expression_state['expression'] = expr_str.replace('^', '**')
    expression_state['just_evaluated'] = False
    update_display()

# 此处绑定键盘事件：
setup_keybindings(root,
     on_button_click=lambda c: on_button_click(c, expression_state, result_state, update_display),
     backspace=lambda: backspace(expression_state, update_display),
     evaluate_expression=lambda: evaluate_expression(expression_state, result_state, update_display)
 )


def calculate():
    global expression
    try:
        result = safe_eval(expression)
        result_var.set(str(result))
    except EvalError as e:
        # 弹窗提示
        messagebox.showerror("计算错误", str(e))

# -----------------------------
# 布局：历史记录 & 显示区
# -----------------------------
history_btn = ttk.Button(
    root, text="历史记录", style="Calc.TButton",
    command=lambda: show_history(root, set_expression)
)
history_btn.pack(fill='x', padx=10, pady=(0,10))

tk.Label(root, textvariable=expression_var,
         font=("微软雅黑", 18), anchor='e',
         bg=SNOW_WHITE, fg=DARK_BLUE)\
  .pack(fill='both', padx=10, pady=5)
tk.Label(root, textvariable=result_var,
         font=("微软雅黑", 24), anchor='e',
         bg=SNOW_WHITE, fg=DARK_BLUE)\
  .pack(fill='both', padx=10, pady=5)

# -----------------------------
# 按钮定义
# -----------------------------
main_buttons = [
    [('C',      lambda: clear_expression(expression_state, result_state, update_display)),
     ('←',      lambda: backspace(expression_state, update_display)),
     ('(',      lambda: on_button_click('(', expression_state, result_state, update_display)),
     (')',      lambda: on_button_click(')', expression_state, result_state, update_display))],
    [('7',      lambda: on_button_click('7', expression_state, result_state, update_display)),
     ('8',      lambda: on_button_click('8', expression_state, result_state, update_display)),
     ('9',      lambda: on_button_click('9', expression_state, result_state, update_display)),
     ('/',      lambda: on_button_click('/', expression_state, result_state, update_display))],
    [('4',      lambda: on_button_click('4', expression_state, result_state, update_display)),
     ('5',      lambda: on_button_click('5', expression_state, result_state, update_display)),
     ('6',      lambda: on_button_click('6', expression_state, result_state, update_display)),
     ('*',      lambda: on_button_click('*', expression_state, result_state, update_display))],
    [('1',      lambda: on_button_click('1', expression_state, result_state, update_display)),
     ('2',      lambda: on_button_click('2', expression_state, result_state, update_display)),
     ('3',      lambda: on_button_click('3', expression_state, result_state, update_display)),
     ('-',      lambda: on_button_click('-', expression_state, result_state, update_display))],
    [('0',      lambda: on_button_click('0', expression_state, result_state, update_display)),
     ('split_dot_comma', None),
     ('=',      lambda: evaluate_expression(expression_state, result_state, update_display)),
     ('+',      lambda: on_button_click('+', expression_state, result_state, update_display))],
]

extra_buttons = [
    [('x²',     lambda: handle_function('square', expression_state, result_state, update_display)),
     ('x³',     lambda: handle_function('cube',   expression_state, result_state, update_display)),
     ('xⁿ',     lambda: on_button_click('^',       expression_state, result_state, update_display)),
     ('x√y',    lambda: insert_root(expression_state, update_display))],
    [('abs',    lambda: handle_function('abs',    expression_state, result_state, update_display)),
     ('log(x,y)',lambda: insert_log(expression_state, update_display)),
     ('e',      lambda: on_button_click('e',       expression_state, result_state, update_display)),
     ('sin',    lambda: handle_function('sin',    expression_state, result_state, update_display))],
    [('cos',    lambda: handle_function('cos',    expression_state, result_state, update_display)),
     ('tan',    lambda: handle_function('tan',    expression_state, result_state, update_display)),
     ('√',      lambda: handle_function('sqrt',   expression_state, result_state, update_display)),
     ('π',      lambda: handle_function('π',      expression_state, result_state, update_display))],
    [('!',      lambda: insert_factorial(expression_state, update_display)),
     ('⑨',      lambda: insert_cirno(result_state, update_display)),
     (None,     None),
     (None,     None)],
]

# -----------------------------
# 布局：按钮区 & 可折叠扩展区
# -----------------------------
button_frame = tk.Frame(root, bg=ICE_BLUE, bd=2, relief="ridge")
button_frame.pack(expand=True, fill='both', padx=10, pady=10)
for r, row in enumerate(main_buttons):
    for c, (txt, cmd) in enumerate(row):
        if txt == 'split_dot_comma':
            sub = tk.Frame(button_frame, bg=ICE_BLUE)
            sub.grid(row=r, column=c, sticky='nsew', padx=2, pady=2)
            ttk.Button(sub, text=',', style="Calc.TButton",
                       command=lambda: on_button_click(',', expression_state, result_state, update_display))\
               .pack(side='left', expand=True, fill='both')
            ttk.Button(sub, text='.', style="Calc.TButton",
                       command=lambda: on_button_click('.', expression_state, result_state, update_display))\
               .pack(side='right', expand=True, fill='both')
        else:
            ttk.Button(button_frame, text=txt, style="Calc.TButton", command=cmd)\
               .grid(row=r, column=c, sticky='nsew', padx=2, pady=2)
for i in range(len(main_buttons)):
    button_frame.rowconfigure(i, weight=1)
for j in range(4):
    button_frame.columnconfigure(j, weight=1)

extra_frame = tk.Frame(root, bg=ICE_BLUE, bd=2, relief="ridge")
for r, row in enumerate(extra_buttons):
    for c, (txt, cmd) in enumerate(row):
        if txt:
            ttk.Button(extra_frame, text=txt, style="Calc.TButton", command=cmd)\
               .grid(row=r, column=c, sticky='nsew', padx=2, pady=2)
for i in range(len(extra_buttons)):
    extra_frame.rowconfigure(i, weight=1)
for j in range(4):
    extra_frame.columnconfigure(j, weight=1)

extra_visible = False
def toggle_extra():
    global extra_visible
    if extra_visible:
        extra_frame.pack_forget()
        toggle_btn.config(text="展开更多功能 ⬇")
    else:
        extra_frame.pack(expand=True, fill='both', padx=10, pady=(0,10))
        toggle_btn.config(text="收起更多功能 ⬆")
    extra_visible = not extra_visible

toggle_btn = ttk.Button(root, text="展开更多功能 ⬇",
                       style="Calc.TButton", command=toggle_extra)
toggle_btn.pack(fill='x', padx=10, pady=(0,10))

# -----------------------------
# 启动主循环
# -----------------------------
root.mainloop()
